<?php
class ControllerPersona extends Controller {
	var $error = array();

	function index() {
		$response =& $this->locator->get('response');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template'); 
		$module   =& $this->locator->get('module');

		$template->set('title','Personas');

		$template->set('content', $this->getList());

		$template->set($module->fetch());

		$response->set($template->fetch('layout.tpl'));
	}

	function insert() 
	{
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');

		$template->set('title', 'Personas');

		if (($request->isPost()) && ($this->validateForm())) 
		{
			$persona_id = $request->get('persona', 'post');
			
		$sql = "insert into personas set persona = '?',clave ='?', nombre ='?', mail ='?', localidad = '?'";
		$database->query($database->parse($sql, $request->get('persona', 'post'),$request->get('persona', 'post'),$request->get('nombre', 'post'),$request->get('mail', 'post'),$request->get('localidad', 'post')));

		$Grupos = $request->get('grupos', 'post', array());
      	foreach ($Grupos as $Grupo) {
        		$sql = "insert into personasgrupos set persona = '?', grupo = '?'";
        		$database->query($database->parse($sql, $persona_id, $Grupo));
	  		}	
	  			
			$cache->delete('persona');

			$session->set('message', 'Se ha actualizado la tabla de personas');
			
			$response->redirect($url->ssl('persona'));
		}

		$template->set('content', $this->getForm());

		$template->set($module->fetch());

		$response->set($template->fetch('layout.tpl'));
	}

	function update() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');


		$template->set('title', 'Personas');

		if (($request->isPost()) && ($this->validateForm())) {
			$sql = "update personas set nombre = '?', mail ='?', localidad='?' where persona = '?'";
			$database->query($database->parse($sql, $request->get('nombre', 'post'), $request->get('mail', 'post'), $request->get('localidad', 'post'), $request->get('persona', 'post')));

			$database->query("delete from personasgrupos where persona = '" . $request->get('persona', 'post') . "'"); 

			$persona_id = $request->get('persona', 'post');	
			$Grupos = $request->get('grupos', 'post', array());
	      	foreach ($Grupos as $Grupo) {
        		$sql = "insert into personasgrupos set persona = '?', grupo = '?'";
        		$database->query($database->parse($sql, $persona_id, $Grupo));
	  		}	
			
			$cache->delete('persona');
			
			$session->set('message', 'Se ha actualizado la tabla personas');
			
			$response->redirect($url->ssl('persona'));
		}

		$template->set('content', $this->getForm());

		$template->set($module->fetch());

		$response->set($template->fetch('layout.tpl'));
	}

	function delete() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');


		$template->set('title', 'Personas');

		if (($request->get('persona')) && ($this->validateDelete())) {
			$database->query("delete from personas where persona = '" . $request->get('persona','get') . "'");

			$cache->delete('persona');
			
			$session->set('message', 'Se ha actualizado la tabla personas');
			
			$response->redirect($url->ssl('persona'));
		}

		$template->set('content', $this->getList());

		$template->set($module->fetch());

		$response->set($template->fetch('layout.tpl'));
	}

	function getList() {
		$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$config   =& $this->locator->get('config');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$session  =& $this->locator->get('session');
		$user  =& $this->locator->get('user');
		$view = $this->locator->create('template');		

    	if ($session->get('persona.persona')) 
		{
			$view->set('persona', $session->get('persona.persona'));
		}
		else
		{
    		$view->set('persona', '');
		}

		if ($session->get('persona.nombre')) 
		{
			$view->set('nombre',$session->get('persona.nombre'));
		}
		else
		{
    		$view->set('nombre', '');
		}

		$cols = array();

		$cols[] = array(
			'name'  => 'Persona',
			'sort'  => 'persona',
			'align' => 'left'
		);

		$cols[] = array(
			'name'  => 'Nombre',
			'sort'  => 'nombre',
			'align' => 'left'
		);

		$cols[] = array(
			'name'  => 'Localidad',
			'sort'  => 'localidad',
			'align' => 'left'
		);

                $cols[] = array(
      		'name'  => 'Acciones',
      		'align' => 'right'
    	);

		
	
		$sort = array(
			'persona',
			'nombre',
                        'localidad',
		);

		if (!$session->get('persona.persona') and !$session->get('persona.nombre'))
		{
			$sql = "select p.persona, p.nombre, p.mail, l.descripcion as localidad from personas p left join localidades l on l.localidad = p.localidad";
		}
		else
		{
			$sql = "selectp.persona, p.nombre, p.mail, l.descripcion as localidad from personas p inner join localidades l on l.localidad = p.localidad where persona like '?' and nombre like '?'";
		}
		
		if (in_array($session->get('persona.sort'), $sort)) {
			$sql .= " order by " . $session->get('persona.sort') . " " . (($session->get('persona.order') == 'desc') ? 'desc' : 'asc');
		} else {
			$sql .= " order by persona asc";
		}

		$results = $database->getRows($database->splitQuery($database->parse($sql, '%' . $session->get('persona.persona') . '%', '%' . $session->get('persona.nombre') . '%'), $session->get('persona.page'), $config->get('config_max_rows')));
		
		$rows = array();

		foreach ($results as $result) {
			$cell = array();

			$cell[] = array(
				'value'   => @$result['persona'],
				'align'   => 'left',
				'default' => 0
			);

			$cell[] = array(
				'value'   => @$result['nombre'],
				'align'   => 'left',
				'default' => 0
			);

			$cell[] = array(
				'value'   => @$result['localidad'],
				'align'   => 'left',
				'default' => 0
			);

                        $action = array();
      		
			if ($user->getPERMISOS($user->getPERSONA(),'persona','M')) {
			$action[] = array(
        		'icon' => 'update.png',
				'text' => $language->get('button_update'),
				'href' => $url->ssl('persona', 'update', array('persona' => $result['persona']))
      		);
			}

			if ($user->getPERMISOS($user->getPERSONA(),'persona','B')) {
			$action[] = array(
        		'icon' => 'delete.png',
				'text' => $language->get('button_delete'),
				'href' => $url->ssl('persona', 'delete', array('persona' => $result['persona']))
      		);
			}
			
      		$cell[] = array(
        		'action' => $action,
        		'align'  => 'right'
      		);
			
			$rows[] = array('cell' => $cell);
		}



		$view->set('heading_title', 'Personas');
		$view->set('heading_description','Gesti&oacute;n de Personas');

		$view->set('text_default', $language->get('text_default'));
		$view->set('text_results', $language->get('text_results', $database->getFrom(), $database->getTo(), $database->getTotal()));

		$view->set('entry_page', $language->get('entry_page'));
		$view->set('entry_search', $language->get('entry_search'));
		$view->set('button_search', $language->get('button_search'));

		$view->set('button_list', $language->get('button_list'));
		$view->set('button_insert', $language->get('button_insert'));
		$view->set('button_exportar', $language->get('button_exportar'));
		
		$view->set('error', @$this->error['message']);

		$view->set('message', $session->get('message'));
		
		$session->delete('message');
		
		$view->set('action', $url->ssl('persona', 'page'));

		$view->set('sort', $session->get('persona.sort'));
		$view->set('order', $session->get('persona.order'));
		$view->set('page', $session->get('persona.page'));
 
		$view->set('cols', $cols);
		$view->set('rows', $rows);

		$view->set('list', $url->ssl('persona'));

		if ($user->getPERMISOS($user->getPERSONA(),'persona','A')) {$view->set('insert', $url->ssl('persona', 'insert'));}

		if ($user->getPERMISOS($user->getPERSONA(),'persona','C'))  $view->set('export', $url->ssl('persona','exportar'));

		$view->set('titulo_ventana', '::. Exportar Personas');
		$page_data = array();

		for ($i = 1; $i <= $database->getPages(); $i++) {
			$page_data[] = array(
				'text'  => $language->get('text_pages', $i, $database->getPages()),
				'value' => $i
			);
		}

		$view->set('pages', $page_data);

		return $view->fetch('content/list_persona.tpl');
	}

        function exportar()
	{
		$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$session  =& $this->locator->get('session');
		set_time_limit(0);
		
		$filtro = 'Filtro:';
		
		$htmlTable="<table border=0 width=180> 
			<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
                        <tr><td colspan=6 align=center style=bold size=14>MCGA</td></tr>
			<tr><td colspan=6 align=center style=bold size=12>4to a&ntilde;o</td></tr>
			<tr><td colspan=6 align=center style=bold size=10>Listado de personas</td></tr>
			<tr><td colspan=6 align=center></td></tr>
			<tr></tr>";

		if (!$session->get('persona.persona') and !$session->get('persona.nombre'))
		{
			$sql = "select p.persona, p.nombre, p.mail from personas p";
		}
		else
		{
			$sql = "select p.persona, p.nombre, p.mail from personas p where p.persona like '%" . $session->get('persona.persona') . "%' and p.nombre like '%" . $session->get('persona.nombre') . "%'";
		}
		

		$sql .= " order by persona asc";
				
		$reporte = $database->getRows($sql);

		foreach ($reporte as $estu)
		{
			
			$htmlTable .= 	"<tr><td colspan=6>__________________________________________________________________________</td></tr>
							<tr>
								<td align=left size=9>Documento</td>
								<td align=left size=9>" . utf8_decode($estu['persona']) . "</td>
							</tr>
							<tr>
								<td align=left size=9>Nombre</td>	
								<td align=left size=9 colspan= 5>" . utf8_decode($estu['nombre']) . "</td>
							</tr>
        						<tr>
								<td align=left size=9>Email</td>
								<td align=left size=9 colspan=5>" . utf8_decode($estu['mail']) . "</td>
							</tr>";				
		}
			 
		$htmlTable .= "</table>";

	define('FPDF_FONTPATH','font/');
	require('javascript/pdf/pdftable.inc.php');
	//ob_end_clean();
	
	$p = new PDFTable();
	$p->AddPage();
	$p->setfont('times','',6);
	$p->htmltable($htmlTable);
	$p->output('','I');
	
	}	
	
	function getForm() {
		$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');

		$view = $this->locator->create('template');

		$view->set('heading_title', 'Personas');
		$view->set('heading_description','Gesti&oacute;n de Personas');

		$view->set('entry_persona', 'Documento:');
		$view->set('entry_nombre', 'Nombre:');
        	$view->set('entry_mail', 'E-mail:');
                $view->set('entry_provincia', 'Provincia:');
                $view->set('entry_localidad', 'Localidad:');
		
		$view->set('text_enabled', $language->get('text_enabled'));
                $view->set('text_disabled', $language->get('text_disabled'));

		$view->set('button_save', $language->get('button_save'));
		$view->set('button_cancel', $language->get('button_cancel'));

		$view->set('error', @$this->error['message']);
		$view->set('error_persona', @$this->error['persona']);
		$view->set('error_nombre', @$this->error['nombre']);
		$view->set('error_mail', @$this->error['mail']);
                $view->set('error_localidad', @$this->error['localidad']);
		
		$view->set('tab_general', $language->get('tab_general'));

		$view->set('action', $url->ssl('persona', $request->get('action'), array('act_codigo' => $request->get('act_codigo'))));
 
		$view->set('cancel', $url->ssl('persona'));

		if (($request->get('persona')) && (!$request->isPost())) {
			$consulta = "select distinct * from personas where persona = '" . $request->get('persona') . "'";
			$persona_info = $database->getRow($consulta);
		}
		if ($request->has('persona', 'post')) {
			$view->set('persona', $request->get('persona', 'post'));
			$persona_id = $request->get('persona', 'post');
		} else {
			$view->set('persona', @$persona_info['persona']);
			$persona_id =@$persona_info['persona'];
		}
		
		if ($request->has('nombre', 'post')) {
			$view->set('nombre', $request->get('nombre', 'post'));
		} else {
			$view->set('nombre', @$persona_info['nombre']);
		}

		if ($request->has('mail', 'post')) {
			$view->set('mail', $request->get('mail', 'post'));
		} else {
			$view->set('mail', @$persona_info['mail']);
		}



                if ($request->has('localidad','post')) {
                    $view->set('localidad',$request->get('localidad','post'));
                 } else {
                    $view->set('localidad',@$persona_info['localidad']);
					//verificar si ya se trae una provincia
                 }

                 $view->set('localidades',$database->getRows('Select * from localidades'));
				 
				    if ($request->has('provincia','post')) {
                    $view->set('provincia',$request->get('provincia','post'));
                } else {
                   if (@$persona_info['localidad'] =='')
				   {
				   		$view->set('provincia','');
				   }
				   else
				   {
						$provincia = $database->getRow("Select provincia from localidades where localidad ='" . $persona_info['localidad'] . "'");
						$view->set('provincia',$provincia['provincia']);
				}
				}

                $view->set('provincias', $database->getRows('select * from provincias'));

        $grupo_data = array();
   
    	$results = $database->getRows("select grupo, descripcion from grupos");

    	foreach ($results as $result) {
  			$user_group = $database->getRow("select * from personasgrupos where persona = '" . $persona_id . "' and grupo = '" . $result['grupo'] . "'");
		
      		
			$grupo_data[] = array(
        		'grupo' => $result['grupo'],
        		'descripcion'  => $result['descripcion'],
        		'persona'  => (isset($user_group) ? $user_group : in_array($result['grupo'], $request->get('grupos', 'post', array())))
      		);
    	}
 
    	$view->set('grupos', $grupo_data);		
		
		
		return $view->fetch('content/persona.tpl');
	}

	function validateForm() 
	{
		$request  =& $this->locator->get('request');
		$user     =& $this->locator->get('user');
		$language =& $this->locator->get('language');

		if ((strlen($request->get('persona', 'post')) == 0)) {
			$this->error['persona'] = 'Debe ingresar el nro de documento';
		}
		if ((strlen($request->get('nombre', 'post')) < 3) || (strlen($request->get('nombre', 'post')) > 100)) {
			$this->error['nombre'] = 'Debe ingresar el nombre';
		}

		if ((strlen($request->get('mail', 'post')) == 0)) {
			$this->error['mail'] = 'Debe ingresar el e-mail';
		}

                if ($request->get('localidad','post') == 0) {
                    $this->error['localidad'] = 'Debe seleccionar la localidad';
                }
                
		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}
	}

	function validateDelete() {
		$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$config   =& $this->locator->get('config');
		$user     =& $this->locator->get('user');
		$language =& $this->locator->get('language');

		if ($config->get('config_act_codigo') == $request->get('persona')) {
			$this->error['message'] = $language->get('error_default');
		}

		//$estudio_info = $database->getRow("select count(*) as total from procesos where persona = '" . (int)$request->get('persona') . "' or act_codigo_reclamado = '" . (int)$request->get('persona') . "'");
		//if ($estudio_info['total']) {
		//	$this->error['message'] = $language->get('error_procesos', $estudio_info['total']);
		//}	
			
		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
        function obtenerLocalidades()
	{
		$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$config   =& $this->locator->get('config');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$response =& $this->locator->get('response');

		$view = $this->locator->create('template');

		$provincia_id = $request->get('provincia_id', 'get');
                $Items = 0;

                $GetLocalidades = "select localidad, descripcion from localidades where provincia ='" . $provincia_id .  "'";

                    $results = $database->getRows($GetLocalidades);

	            //$optLocalidades = $GetLocalidades;

                    foreach($results as $result):   //crea un option por cada localidad que encuentra
               			if ($Items == 0)
						{
							$optLocalidades ="<option value='". $result['localidad'] ."'>". $result['descripcion'] ."</option>";
						}
						else
						{
							$optLocalidades.="<option value='". $result['localidad'] ."'>". $result['descripcion'] ."</option>";
						}
						$Items +=1;
                    endforeach;
        
                    echo $optLocalidades; //Devolvemos las opciones de la lista localidades

	}

	function page() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$url      =& $this->locator->get('url');
		$session  =& $this->locator->get('session');

		$session->set('persona.persona',$request->get('persona','post'));

		$session->set('persona.nombre',$request->get('nombre','post'));
	
		if (($request->has('page', 'post')) || ($request->has('search', 'post'))) {
			$session->set('persona.page', $request->get('page', 'post'));
		}

		if ($request->has('sort', 'post')) {
			$session->set('persona.order', (($session->get('persona.sort') == $request->get('sort', 'post')) && ($session->get('persona.order') == 'asc')) ? 'desc' : 'asc');
		}

		if ($request->has('sort', 'post')) {
			$session->set('persona.sort', $request->get('sort', 'post'));
		}

		$response->redirect($url->ssl('persona'));
	}	
}
?>